"""
FastAPI主应用程序
"""
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import uvicorn
import os
from pathlib import Path
from app.config import settings
from app.database import create_tables, close_db_connections
from app.routers import themes, articles, publish
from app.utils.logger import logger
from app.utils.exceptions import BaseCustomException


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("正在启动微信公众号文章生成工具...")
    
    # 创建数据库表（开发模式下跳过）
    if settings.environment == "development":
        logger.warning("开发模式：跳过数据库初始化")
    else:
        try:
            await create_tables()
            logger.info("数据库表创建/检查完成")
        except Exception as e:
            logger.error(f"数据库初始化失败: {str(e)}")
            raise
    
    # 测试外部服务连接（开发模式下跳过）
    if settings.environment == "development":
        logger.warning("开发模式：跳过外部服务连接测试")
    else:
        try:
            from app.services.wechat_service import wechat_service
            connection_ok = await wechat_service.test_connection()
            if connection_ok:
                logger.info("微信API连接测试成功")
            else:
                logger.warning("微信API连接测试失败")
        except Exception as e:
            logger.warning(f"微信API连接测试异常: {str(e)}")
    
    logger.info("应用启动完成")
    
    yield  # 应用运行期间
    
    # 关闭时执行
    logger.info("正在关闭应用...")
    if settings.environment != "development":
        await close_db_connections()
    logger.info("应用已关闭")


# 创建FastAPI应用
app = FastAPI(
    title="微信公众号文章自动生成工具",
    description="""
    自动化微信公众号内容创作助手
    
    ## 功能特色
    
    * **AI内容生成**: 集成DeepSeek AI，自动生成高质量文章标题、摘要和正文
    * **智能配图**: 使用通义万相AI生成文章封面和配图
    * **微信集成**: 直接上传素材到微信公众号，并发布到草稿箱
    * **主题管理**: 支持多主题配置，个性化内容生成
    * **批量操作**: 支持批量生成文章和批量发布
    
    ## 使用流程
    
    1. **创建主题**: 在主题管理中添加内容主题和关键词
    2. **生成文章**: 选择主题自动生成文章内容和配图
    3. **发布草稿**: 将生成的文章发布到微信公众号草稿箱
    4. **管理内容**: 查看发布历史和管理素材
    
    ## 技术栈
    
    * **后端**: FastAPI + SQLAlchemy + MySQL
    * **AI服务**: DeepSeek API + 通义万相API
    * **微信集成**: 微信公众号开放平台API
    """,
    version="1.0.0",
    contact={
        "name": "微信公众号文章生成工具",
        "email": "support@example.com",
    },
    license_info={
        "name": "MIT License",
    },
    lifespan=lifespan
)

# CORS中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.exception_handler(BaseCustomException)
async def custom_exception_handler(request: Request, exc: BaseCustomException):
    """自定义异常处理器"""
    logger.error(f"自定义异常: {exc.message}")
    return JSONResponse(
        status_code=422,
        content={
            "error": True,
            "message": exc.message,
            "error_type": exc.error_type.value if exc.error_type else None,
            "error_code": exc.error_code.value if exc.error_code else None
        }
    )


@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理器"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "error": True,
            "message": "服务器内部错误",
            "detail": str(exc) if settings.environment == "development" else None
        }
    )


# 注册路由
app.include_router(themes.router, prefix="/api")
app.include_router(articles.router, prefix="/api")
app.include_router(publish.router, prefix="/api")

# 挂载静态文件
static_dir = Path(__file__).parent.parent / "static"
if static_dir.exists():
    app.mount("/static", StaticFiles(directory=static_dir), name="static")


@app.get("/", tags=["系统"])
async def root():
    """根路径 - 返回Web管理界面"""
    static_dir = Path(__file__).parent.parent / "static"
    index_file = static_dir / "index.html"
    
    if index_file.exists():
        return FileResponse(index_file)
    else:
        return {
            "message": "微信公众号文章自动生成工具",
            "version": "1.0.0",
            "status": "running",
            "docs_url": "/docs",
            "redoc_url": "/redoc"
        }


@app.get("/health", tags=["系统"])
async def health_check():
    """健康检查接口"""
    if settings.environment == "development":
        return {
            "status": "healthy",
            "timestamp": "2025-09-01T00:00:00Z",
            "environment": "development",
            "services": {
                "database": "skipped (dev mode)",
                "wechat_api": "skipped (dev mode)",
                "deepseek_api": "skipped (dev mode)", 
                "tongyi_api": "skipped (dev mode)"
            }
        }
    else:
        return {
            "status": "healthy",
            "timestamp": "2025-09-01T00:00:00Z",
            "services": {
                "database": "connected",
                "wechat_api": "available",
                "deepseek_api": "available", 
                "tongyi_api": "available"
            }
        }


@app.get("/api/config/info", tags=["配置"])
async def get_config_info():
    """获取配置信息（不包含敏感数据）"""
    return {
        "app_port": settings.app_port,
        "environment": settings.environment,
        "database_host": settings.db_host,
        "database_name": settings.db_name,
        "wechat_app_id": settings.wechat_app_id,
        "deepseek_base_url": settings.deepseek_base_url,
        "tongyi_base_url": settings.tongyi_base_url,
        "max_concurrent_generations": settings.max_concurrent_generations
    }


if __name__ == "__main__":
    # 直接运行应用
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=settings.app_port,
        reload=settings.environment == "development",
        log_level="info"
    )